<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Repositories\MenuRepository;
use App\Http\Requests\MenuRequest;
use App\Services\PHPTree;

class MenuController extends AdminController
{
    public function __construct(MenuRepository $menu)
    {
        $this->menu = $menu;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $menuTree = (new PHPTree($this->menu->all()->toArray()))->render();

        $navTopLabel = 'menu';

        return view('admin.menu', compact('menuTree', 'navTopLabel'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create(Request $request)
    {
        $pid = $request->input('pid');
        $topMenu= $this->menu->topMenuSelectArray();

        $navTopLabel = 'menu';

        return view('admin.menu_add', compact('pid', 'topMenu', 'navTopLabel'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(MenuRequest $request)
    {
        $result = $this->menu->create($request->all());

        if ($result) {
            return back()->with('success', '菜单添加成功');
        }

        return back()->with('error', '菜单添加失败');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $data    = $this->menu->find($id);
        $topMenu = $this->menu->topMenuSelectArray();

        $navTopLabel = 'menu';

        return view('admin.menu_edit', compact('data', 'topMenu', 'navTopLabel'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(MenuRequest $request, $id)
    {
        $result = $this->menu->updateFind($request->all(), $id);

        if ($result) {
            return redirect()->route('admin.menu.index')->with('success', '菜单更新成功'); 
        }

        return back()->with('error', '菜单更新失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(Request $request, $id)
    {
        $result = $this->menu->delete($id);

        if ($result) {
            flash('success', '菜单删除成功');
            return response()->json(['code' => 200]);
        }

        flash('error', '菜单删除失败');
        return response()->json(['code' => 500]);
    }

    // 排序
    public function sort(Request $request)
    {
        $orders = $request->input('order');

        if (!empty($orders)) {
            $this->menu->updateSort($orders);
        }

        return back()->with('success', '菜单排序成功');
    }
}